package com.gin.table.util;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author gin
* @date 2021/4/22
*/
public class ClasspathSqlLoader {

    public static List<String> getSqlList(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return Collections.emptyList();
        }
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        InputStream inputStream = classLoader.getResourceAsStream(filePath);
        if (null != inputStream) {
            System.out.println("get file from :" + filePath);
            return getSqlList(inputStream);
        }
        System.out.println("get file does not exists :" + filePath);
        return Collections.emptyList();
    }

    /**
     * 通用从input stream读取sql list
     *
     * @param inputStream input stream
     * @return sql list
     */
    public static List<String> getSqlList(InputStream inputStream) {
        if (null != inputStream) {
            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
                List<String> lines = bufferedReader.lines()
                        .filter(StringUtils::isNotEmpty)
                        .collect(Collectors.toList());

                String str = String.join("\n", lines);
                return Arrays.stream(str.split(";")).collect(Collectors.toList());
            } catch (IOException ignored) {
            }
        }
        return Collections.emptyList();
    }

}